<?php


namespace App\Http\Middleware;
use App\Models\Customer;
use App\Models\CustomerUser;
use Closure;
use Illuminate\Auth\Middleware\Authenticate;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class CustomerMiddleware extends Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  Request $request
     * @param Closure $next
     * @param  string[] ...$guards
     * @return mixed
     *
     */
    public function handle($request, Closure $next, ...$guards)
    {
        $id = $request->route('customer');

        /** @var Customer $customer */
        $customer = Customer::query()->where('id', '=', $id)->first();


        if(empty($customer)){
            throw new NotFoundHttpException('不存在或者客户不可用');
        }

        if(!$customer->isNormal()){
            throw new NotFoundHttpException('账号不正常，请联系相关业务人员！');
        }
        $request->merge(['customer_id' => $customer->getKey()]);
        $request->route()->forgetParameter('customer');
        /** @var CustomerUser $user */
        $user = auth('customer')->user();
        // 是否有登录
        if ($user === null) {
            return $next($request);
        }
        if ($user->getAttribute('customer_id') === $customer->getKey()) {
            return $next($request);
        }
        throw new NotFoundHttpException('请检查是杏存在这个用户！');
    }
}
